package com.tich.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tich.api.client.UserClient;
import com.tich.api.domain.dto.BalanceDeductDTO;
import com.tich.constant.ExceptionConstant;
import com.tich.context.UserContext;
import com.tich.enumration.OrderStatus;
import com.tich.exception.OrderStatusException;
import com.tich.exception.PayFailException;
import com.tich.order.domain.entity.Orders;
import com.tich.order.mapper.OrderMapper;
import com.tich.order.service.PayService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class PayServiceImpl implements PayService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserClient userClient;

    /**
     * 支付订单
     * @param orderId
     * @return
     * */
    @GlobalTransactional
    public void payOrder(Long orderId) {
        //1.查询订单
        Orders orders = orderMapper.selectById(orderId);
        if(orders.getOrderStatus() != OrderStatus.UNPAID.getCode()){
            //如果不是待支付则不能修改
            throw new OrderStatusException(ExceptionConstant.ORDER_CANCEL_OR_PAID);
        }
        //2.扣除余额
        BalanceDeductDTO balanceDeductDTO = new BalanceDeductDTO()
                .setUserId(UserContext.getCurrentId())
                .setDeduct(orders.getMoney());
        if(!userClient.balanceDeduct(balanceDeductDTO).getData()){
            throw new PayFailException(ExceptionConstant.PAY_FAIL);
        }
        //3.修改订单状态
        LambdaUpdateWrapper<Orders> orderLambdaUpdateWrapper = Wrappers.lambdaUpdate(Orders.class)
                .set(Orders::getOrderStatus, OrderStatus.PAID.getCode())
                .set(Orders::getPayOrderTime, LocalDateTime.now())
                .eq(Orders::getId, orderId);
        orderMapper.update(orderLambdaUpdateWrapper);
    }



}
